package alf.mapping.view.visuals;
import alf.mapping.dto.maps.Item;
import alf.mapping.dto.maps.Link;
import alf.mapping.dto.maps.Room;
import alf.mapping.view.Env;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;

public class VisualElement {
	private Bitmap bitmap;
	Item item;
	private Paint paint;

	public VisualElement(Item e, Bitmap b, Paint paint) {
		this.bitmap = b;
		this.item = e;
		Rect rect = e.getRect();
		if (rect.height()<=0) {
			rect.bottom =  rect.top + b.getHeight();
		}
		if (rect.width()<=0){
		rect.right = rect.left + b.getWidth();
		}
		this.paint = paint;
	}

	public Point getSize() {
		Rect r = item.getRect();
		return new Point(r.width(), r.height());
	}
	public String toString() {
		return item.toString();
	}

	public void setItem(Item entity) {
		this.item = entity;
	}

	public Item getItem() {
		return item;
	}

	public void setBitmap(Bitmap b) {
		this.bitmap = b;
	}

	public void onDraw(Canvas canvas, Rect transf, int zoom) {
		Rect dst = new Rect(item.getRect());
		transform(dst, transf, zoom);
		canvas.drawBitmap(bitmap, null,	dst,	paint);

		canvas.drawText(item.getName(), dst.left, dst.bottom + paint.getTextSize(), paint);
	}

	public void drawLinks(Canvas canvas, Rect viewport, int zoom, Room r) {
		if (getItem().getLinks() != null) {
			for (Link link : getItem().getLinks()) {
				if (link.getDestination() != null && link.isVisible()
						&& r.equals(link.getDestination().getDiagram())) {
					drawLink(link, canvas, viewport, zoom, r);
				}
			}
		}
	}

	public void drawLink(Link link, Canvas canvas, Rect viewport, int zoom, Room room) {
		//Env.debug("draw link: ");
		Rect bounds = new Rect();
		bounds.left = this.getItem().getRect().centerX();
		bounds.top = this.getItem().getRect().centerY();
		bounds.right = link.getDestination().getItem().getRect().centerX();
		bounds.bottom = link.getDestination().getItem().getRect().centerY();
		transform(bounds, viewport, zoom);
		Path path = new Path();
		path.moveTo(bounds.left, bounds.top);
		path.lineTo(bounds.right, bounds.bottom);
		path.setLastPoint(bounds.right,bounds.bottom);
		canvas.drawPath(path, paint);
	}

	public Rect rect() {
		return item.getRect();
	}

	public static void transform(Rect dst, Rect transf, int zoom) {
		dst.offset(-transf.left, -transf.top);
		dst.left = (zoom * dst.left) / 100;
		dst.top = (zoom * dst.top) / 100;
		dst.right = (zoom * (dst.left + dst.width()) / 100);
		dst.bottom = (zoom * (dst.top + dst.height()) / 100);
	}

	public static void untransform(Rect dst, Rect transf, int zoom) {
		dst.left = (100 * dst.left) / zoom;
		dst.top = (100 * dst.top) / zoom;
		dst.right = (100 * (dst.left + dst.width()) / zoom);
		dst.bottom = (100 * (dst.top + dst.height()) / zoom);
		dst.offset(transf.left, transf.top);
	}
}
